<?php
/**
 * wechat php test
 */
//define your token
define("TOKEN", "gaofeifiy");
$wechatObj = new wechatCallbackapiTest();

//$wechatObj->createMenu(); //要创建菜单就调用一下这个函数



if(isset($_GET["echostr"])){                //当有这个的时候就是验证 没有的时候就直接回复消息
    $wechatObj->valid();
}else{
//    $wechatObj->responseMsg();            //当用户发送消息时自动回复消息


    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];  //接收微信服务器返回的信息，是xml类型
    libxml_disable_entity_loader(true);         //做安全防御用的
    $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);  //将xml格式的信息解析成对象的格式

    $toUser = $postObj->FromUserName;           //用户的微信号id
    $fromUser = $postObj->ToUserName;           //你的微信号id
    $time = time();
    //如果是事件类型
    if($postObj->MsgType == 'event'){
        //如果是订阅
        if($postObj->Event == 'subscribe'){
            //给用户发送信息
            $content = '欢迎使用微信订阅号';

            $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>
str;
            echo $str;exit;


        }
        //如果是取消订阅
        if($postObj->Event == 'unsubscribe'){
            //网站可以把粉丝表里面的记录删除
        }
        //如果是点击事件,则也是返回一个消息提示什么的
        if($postObj->Event == 'CLICK'){
            //给用户发送信息
            $content = '你是点了是吧?'.$postObj->EventKey;

            $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>
str;
            echo $str;exit;
        }
        //如果是扫码加消息提示事件
        if($postObj->Event == 'scancode_waitmsg'){
            //给用户发送信息
            $content ='二维码内的信息是:'.$postObj->ScanCodeInfo->ScanResult.'还有类型是:'.$postObj->ScanCodeInfo->ScanType;  //这里是 ScanCodeInfo下有两个节点 一个ScanResult是扫描到的信息,一个ScanType是扫描的类型;

            $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>
str;
            echo $str;exit;
            //这里的流程是微信扫描二维码 将信息直接发送给服务器, 如果我想让用户看是什么信息再发给用户  或者就是根据扫到的信息给用户发送相应的东西,
            //总之用户是无法直接看到二维码中的消息的
        }

        //如果是扫码推送事件
        if($postObj->Event == 'scancode_push'){
           //这里和上面的那个扫码不一样  这个是直接调用微信扫码工具,而且直接显示扫描到的信息  同时将扫描到的信息发送给服务器一份
        }


    }

    if($postObj->MsgType == 'text'){ //如果是文本类型
        switch($postObj->Content){
            case '1' :
                $content = '你发送的是一吗?';
                break;
            case '电话':
                $content = '我的电话是:18333636949';
                break;
            case '北京天气':
                $content = BJweather();
                $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>
str;
                echo $str;exit;
                break;
            case '图文':
                $data = array(
                    array(
                        'title' => '图片一',
                        'description'=>'图片描述一',
                        'picurl' =>'http://i6.qhimg.com/dr/270_500_/t014721dd43d6cf0733.jpg',
                        'url' =>'www.baidu.com'
                    ),
                    array(
                        'title' => '图片二',
                        'description'=>'图片描述二',
                        'picurl' =>'http://www.mangowed.com/chaoliuImage/1-120210125044.jpg',
                        'url' =>'www.so.com'
                    ),
                );
                $count = count($data);   //有多少篇文章
                $output = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>{$count}</ArticleCount>
<Articles>
str;
                foreach($data as $v){
                    $output.=<<<str
<item>
<Title><![CDATA[{$v['title']}]]></Title>
<Description><![CDATA[{$v['description']}]]></Description>
<PicUrl><![CDATA[{$v['picurl']}]]></PicUrl>
<Url><![CDATA[{$v['url']}]]></Url>
</item>
str;
                }
                $output.=<<<str
</Articles>
</xml>
str;
            echo $output;exit;
            break;
            default:
                $content = '现在的关键词只有 1,电话,图文和北京天气哦';
        }
        $str = <<<str
<xml>
<ToUserName><![CDATA[{$toUser}]]></ToUserName>
<FromUserName><![CDATA[{$fromUser}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>
str;
        echo $str;exit;
    }


}

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            if(!empty( $keyword ))
            {
                $msgType = "text";
                $contentStr = "消息成功接收";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo "Input something...";
            }

        }else {
            echo "";
            exit;
        }
    }

    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function getToken(){
        //初始化
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxfc6a551f94e63e8b&secret=d4624c36b6795d1d99dcf0547af5443d");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);            //当访问https时校验证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        //跳过证书校验

        $access_token = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        $data = json_decode($access_token,true);
        return $data['access_token'];
    }

    public function createMenu(){
        $data = '{
     "button":[
     {
          "type":"click",
          "name":"菜单233",
          "key":"V1001_TODAY_MUSIC"
      },
      {
          "name":"多功能",
          "sub_button":[
           {
               "type":"scancode_waitmsg",
               "name":"扫码带提示",
               "key": "rselfmenu_0_0",
            },
            {
                "type": "scancode_push",
                "name": "扫码推事件",
                "key": "rselfmenu_0_1",
            },
            {
                 "type": "pic_sysphoto",
                 "name": "系统拍照发图",
                 "key": "rselfmenu_1_0",
            },
            {
               "name": "发送位置",
               "type": "location_select",
               "key": "rselfmenu_2_0"
            }]
      },
      {
           "name":"菜单244",
           "sub_button":[
           {
               "type":"view",
               "name":"sogou搜索",
               "url":"http://www.soso.com/"
            },
            {
               "type":"view",
               "name":"qq视频",
               "url":"http://v.qq.com/"
            },
            {
               "type":"click",
               "name":"赞一下我们",
               "key":"V1001_GOOD"
            }]
       }]
 }';

        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=jTYhP6S8kILOE5yNO6d61EEC0JnjVR8TpiR1F3mKSV7teKP2bftYNlyN3z04iaFcNHq8L4Cc1su_7671YrwQyTUi_VuA2zIOGyXb0RnT-NwITPdAGADOK";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            // 返回值而不是直接输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);            //当访问https时校验证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);        //跳过证书校验
        $output = curl_exec($ch);
        curl_close($ch);

        var_dump($output);die;

    }
}

function BJweather(){                    //调用了一个百度api_store里的一个api 获取北京天气(其实可以查不同的地区,需要地区id支持)
    $ch = curl_init();
    $url = 'http://apis.baidu.com/heweather/weather/free?city=beijing';
    $header = array(
        'apikey: 988c4a8174ba5bcea59d0b633feba489', //我自己的api
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);// 添加apikey到header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    //得到的值不直接输出

    curl_setopt($ch , CURLOPT_URL , $url);          // 执行HTTP请求
    $res = curl_exec($ch);
    echo '<pre>';
    $data = json_decode($res,true);
    $forecast = $data['HeWeather data service 3.0'][0]['hourly_forecast'];  //调用了其中一部分内容 最近几小时的天气播报

    $str = '<h2>北京未来几小时的天气预报</h2>';
    foreach ($forecast as $k => $vv) {
        $str.='<h4>时间:'.$vv['date'].';</h4>';
        $str.='相对湿度:'.$vv['hum'].';<br>';
        $str.='降水量:'.$vv['pop'].';<br>';
        $str.='气压:'.$vv['pres'].';<br>';
        $str.='温度:'.$vv['tmp'].';<br>';
        $str.='风向:'.$vv['wind']['dir'].$vv['wind']['sc'].';<br>';
        $str.='>>>>>>>>>>>>>>>>>>>>>>>>>>';
    }
    return $str;
}

//$api = '988c4a8174ba5bcea59d0b633feba489'; //百度天气的api
